package cn.edu.scau.cmi.huangmaoqin.hibernate.dao;

import java.util.List;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.Transaction;
import cn.edu.scau.cmi.huangmaoqin.hibernate.domain.Student;
import cn.edu.scau.cmi.huangmaoqin.hibernate.domain.Teacher;

public class TeacherDAO extends BaseHibernateDAO {

	public void save(Teacher teacher, Set<Student> students) {
		try {
			Transaction transactionT = getSession().beginTransaction();
			getSession().save(teacher);
			// 提交事务
			transactionT.commit();

			for (Student student : students) {
				Teacher oldT = student.getTeacher();
				student.setTeacher(teacher);
				new StudentDAO().update(student, oldT);
			}
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void delete(Teacher teacher) {
		try {
			// 要删除老师,必须先将关联的学生信息改掉,学生单方面解除关系
			Set<Student> students = teacher.getStudents();
			for (Student student : students) {
				student.setTeacher(null);
				new StudentDAO().update(student);
			}

			Transaction transactionT = getSession().beginTransaction();
			getSession().delete(teacher);
			transactionT.commit();

		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void update(Teacher teacher, Set<Student> oldStudents) {
		try {
			// 以前学生单方面断掉关系
			for (Student student : oldStudents) {
				student.setTeacher(null);
				new StudentDAO().update(student);
			}
			// 新的学生单方面建立关系
			Set<Student> students = teacher.getStudents();
			for (Student student : students) {
				// 得到之前的老师
				Teacher oldT = (student == null ? null : student.getTeacher());
				student.setTeacher(teacher);
				new StudentDAO().update(student, oldT);
			}
			// 老师建立关系
			Transaction transactionT = getSession().beginTransaction();
			getSession().update(teacher);
			transactionT.commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void update(Teacher teacher) {
		try {
			Transaction transactionT = getSession().beginTransaction();
			getSession().update(teacher);
			transactionT.commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public Teacher findById(Long id) {
		try {
			Teacher instance = (Teacher) getSession().get("cn.edu.scau.cmi.huangmaoqin.hibernate.domain.Teacher", id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		try {
			String queryString = "from Teacher as model where model." + propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findAll() {
		try {
			String queryString = "from Teacher";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
